package com.example.duanlei417.mypro2.view;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;

import com.example.duanlei417.mypro2.R;

public class TestProgressBar extends View {
    private final String TAG = "TestProgressBar";
    //画笔
    private Paint paintText, paintBackGround, paintBar;
    //颜色
    private int backGroundColor = Color.GRAY, barColor = Color.RED;

    //图片
    private Drawable drawable = null;

    //Drawable的宽高半径
    private int halfDrawableWidth = 0, halfDrawableHeight = 0;

    //Drawable高度偏移量
    private int drawableHeightOffset = 0;

    //进度值和最大值
    private int progress = 0, max = 100;
    //进度条当前进度中心点
    private int x, y;

    //进度条宽高
    private int progressWidth = 100, progressHeight = 30;
    //进度条高度偏移量
    private int progressHeightOffset = 0;

    private RectF rectFBG = new RectF(), rectFPB = new RectF();

    //是否使用颜色渐变器
    private boolean isGradient = true;
    //颜色渐变器
    private LinearGradient linearGradient;

    private int numTextSize;

    private int gradientStartColor = Color.RED, gradientEndColor = Color.YELLOW;

    private float minValue = 0;
    private float maxValue = 5.8f;

    private int lastProgress = 50;

    public TestProgressBar(Context context) {
        super(context);
        init();
    }

    public TestProgressBar(Context context, AttributeSet attrs) {
        super(context, attrs);

        //获取xml属性
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TestProgressBar);
        backGroundColor = typedArray.getColor(R.styleable.TestProgressBar_backGroundColor, Color.GRAY);
        drawable = typedArray.getDrawable(R.styleable.TestProgressBar_drawable);
        halfDrawableWidth = (int)typedArray.getDimension(R.styleable.TestProgressBar_halfDrawableWidth, 35);
        halfDrawableHeight = (int)typedArray.getDimension(R.styleable.TestProgressBar_halfDrawableHeight, 35);
        drawableHeightOffset = (int)typedArray.getDimension(R.styleable.TestProgressBar_drawableHeightOffset, 0);

        progress = typedArray.getInt(R.styleable.TestProgressBar_progress, 0);
        max = typedArray.getInt(R.styleable.TestProgressBar_max, 100);

        progressHeight = (int)typedArray.getDimension(R.styleable.TestProgressBar_progressHeight, 30);
        progressHeightOffset = (int)typedArray.getDimension(R.styleable.TestProgressBar_progressHeightOffset, 0);

        gradientStartColor = typedArray.getColor(R.styleable.TestProgressBar_gradientStartColor, Color.RED);
        gradientEndColor = typedArray.getColor(R.styleable.TestProgressBar_gradientEndColor, Color.YELLOW);

        numTextSize = (int)typedArray.getDimension(R.styleable.TestProgressBar_numTextSize, 20);

        typedArray.recycle();
        init();
    }

    public TestProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    //初始化
    private void init() {
        //初始化画笔
        paintText = new Paint();
        paintText.setColor(gradientEndColor);
        paintText.setTextSize(numTextSize);
        paintText.setStyle(Paint.Style.FILL);
        paintText.setTextAlign(Paint.Align.CENTER);
        paintText.setAntiAlias(true);

        paintBackGround = new Paint();
        paintBackGround.setColor(backGroundColor);
        paintBackGround.setAntiAlias(true);

        paintBar = new Paint();
        paintBar.setColor(barColor);
        paintBar.setAntiAlias(true);

        //是否需要渐变器
        if (isGradient) {
            //在PreDraw时获取View属性,因为在初始化的时候View还没进行Measure
            getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    getViewTreeObserver().removeOnPreDrawListener(this);
                    linearGradient = new LinearGradient(0, progressHeight / 2, progressWidth,
                            progressHeight / 2, gradientStartColor, gradientEndColor,
                            Shader.TileMode.CLAMP);
                    paintBar.setShader(linearGradient);
                    return false;
                }
            });
        }

        initAnimator = new MyAnimation();
    }

    MyAnimation initAnimator;

    public class MyAnimation extends Animation {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            //interpolatedTime从0渐变成1,到1时结束动画,持续时间由setDuration（time）方法设置
            int tempProgress = (int) ((float) lastProgress * interpolatedTime);
            setProgress(tempProgress);
        }

        @Override
        public void initialize(int width, int height, int parentWidth, int parentHeight) {
            super.initialize(width, height, parentWidth, parentHeight);
            setFillAfter(true);
            setInterpolator(new LinearInterpolator());
        }
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        //获取进度条当前进度的中心点坐标
        x = (progressWidth - halfDrawableWidth) * progress / max + halfDrawableWidth;
        y = getHeight() / 2;

        drawBar(canvas);
        drawText(canvas);
        drawPicture(canvas);
    }

    //画进度条
    private void drawBar(Canvas canvas) {
        rectFBG.set(0, y - progressHeight / 2 + progressHeightOffset,
                progressWidth, y + progressHeight / 2 + progressHeightOffset);
        canvas.drawRoundRect(rectFBG, progressHeight/2, progressHeight/2, paintBackGround);

        rectFPB.set(0, y - progressHeight / 2 + progressHeightOffset,
                x, y + progressHeight / 2 + progressHeightOffset);
        canvas.drawRoundRect(rectFPB, progressHeight/2, progressHeight/2, paintBar);
    }

    @SuppressLint("DefaultLocale")
    private void drawText(Canvas canvas) {
        paintText.setColor(Color.parseColor("#c5c5c5"));
        paintText.setTextSize(numTextSize);

        paintText.setTextAlign(Paint.Align.LEFT);
        canvas.drawText(String.valueOf(minValue), 0, canvas.getHeight(), paintText);

        paintText.setTextAlign(Paint.Align.RIGHT);
        canvas.drawText(String.valueOf(maxValue), progressWidth, canvas.getHeight(), paintText);

        paintText.setColor(gradientEndColor);
        paintText.setTextAlign(Paint.Align.CENTER);
        paintText.setTextSize(numTextSize + 5);

        canvas.drawText(String.format("%.1f", maxValue * ((float) progress / 100)), x,
                canvas.getHeight(), paintText);
    }

    //画图
    private void drawPicture(Canvas canvas) {
        if (drawable == null) {
            Log.e(TAG, "drawable is null");
            return;
        }
        drawable.setBounds(x - halfDrawableWidth,
                getHeight() / 2 - halfDrawableHeight + drawableHeightOffset,
                x + halfDrawableWidth,
                getHeight() / 2 + halfDrawableHeight + drawableHeightOffset);
        drawable.draw(canvas);
    }

    //重写onMeasure，以自定义获取进度条的宽高
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);


        if (getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT) {
            //在这里实现计算需要wrap_content时需要的宽
            width = halfDrawableWidth * 2;
        }
        if (getLayoutParams().height == ViewGroup.LayoutParams.WRAP_CONTENT) {
            //在这里实现计算需要wrap_content时需要的高
            height = halfDrawableHeight * 2;
        }

        progressWidth = width;

        //如果有图片，就为图片预留空间
        if (drawable != null) {
            progressWidth = width - halfDrawableWidth;
        }

        //传入处理后的宽高
        setMeasuredDimension(width, height);
    }

    //设置进度
    public void setProgress(int progress) {
        if (progress <= max) {
            this.progress = progress;
        } else if (progress < 0) {
            this.progress = 0;
        } else {
            this.progress = max;
        }
        postInvalidate();
    }

    public void setProgressWithAnim(int progress, int duration) {
        lastProgress = progress;
        initAnimator.setDuration(duration);
        startAnimation(initAnimator);
    }

    @Override
    protected void onWindowVisibilityChanged(int visibility) {
        super.onWindowVisibilityChanged(visibility);
        Log.e(TAG, "onWindowVisibilityChanged: visibility:" + visibility);


    }
}
